package jsf;

import java.io.IOException;
import jpa.entities.Students;
import jsf.util.JsfUtil;
import jsf.util.PaginationHelper;
import jsf.session.StudentsFacade;

import java.io.Serializable;
import java.util.ResourceBundle;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import javax.faces.model.SelectItem;
import javax.servlet.http.HttpServletRequest;
import jpa.entities.Classes;
import jpa.entities.Staff;

@ManagedBean(name = "studentsController")
@SessionScoped
public class StudentsController implements Serializable {

    private Students current;
    private DataModel items = null;
    @EJB
    private jsf.session.StudentsFacade ejbFacade;
    private PaginationHelper pagination;
    private int selectedItemIndex;
    
    public StudentsController() {
    }
    
    public Students getSelected() {
        if (current == null) {
            current = new Students();
            selectedItemIndex = -1;
        }
        FacesContext context = FacesContext.getCurrentInstance();
        Students student = (Students) context.getExternalContext().getSessionMap().get("IsStudent");
        if(student !=null)
        {
        current = getProfile();
        return current;
        }
        return current;
    }

    private StudentsFacade getFacade() {
        return ejbFacade;
    }

    public PaginationHelper getPagination() {
        if (pagination == null) {
            pagination = new PaginationHelper(10) {
                @Override
                public int getItemsCount() {
                    return getFacade().count();
                }

                @Override
                public DataModel createPageDataModel() {
                    return new ListDataModel(getFacade().findRange(new int[]{getPageFirstItem(), getPageFirstItem() + getPageSize()}));
                }
            };
        }
        return pagination;
    }

    public String prepareList() {
        recreateModel();
        return "List";
    }
    public Students getProfile()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        Students student = (Students) context.getExternalContext().getSessionMap().get("IsStudent");
        Students s = (Students) getFacade().getProfile(student.getUserName());
        return s;
    }
    public String prepareView() {
        //current = (Students) getItems().getRowData();
        current = getProfile();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "View";
    }

    public String prepareCreate() {
        current = new Students();
        selectedItemIndex = -1;
        return "Create";
    }

    public String create() {
        try {
            getFacade().create(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("StudentsCreated"));
            return prepareCreate();
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }

    public String prepareEdit() {
        current = (Students) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        return "Edit";
    }

    public String update() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("StudentsUpdated"));
            return "View";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    public String updateForUser() {
        try {
            getFacade().edit(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("StudentsUpdated"));
            return "/faces/user/studentCourse/List.xhtml";
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
            return null;
        }
    }
    private Classes classes;

    public Classes getClasses() {
        return classes;
    }

    public void setClasses(Classes classes) {
        this.classes = classes;
    }
    
    public String findAllStudentByClass() {
        try {
            items = new ListDataModel(ejbFacade.findStudenteByClassesId(classes));
            return "/faces/admin/students/List.xhtml?facesredirect";

        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }
    public String destroy() {
        current = (Students) getItems().getRowData();
        selectedItemIndex = pagination.getPageFirstItem() + getItems().getRowIndex();
        performDestroy();
        recreatePagination();
        recreateModel();
        return "List";
    }

    public String destroyAndView() {
        performDestroy();
        recreateModel();
        updateCurrentItem();
        if (selectedItemIndex >= 0) {
            return "View";
        } else {
            // all items were removed - go back to list
            recreateModel();
            return "List";
        }
    }

    private void performDestroy() {
        try {
            getFacade().remove(current);
            JsfUtil.addSuccessMessage(ResourceBundle.getBundle("/resources/Bundle").getString("StudentsDeleted"));
        } catch (Exception e) {
            JsfUtil.addErrorMessage(e, ResourceBundle.getBundle("/resources/Bundle").getString("PersistenceErrorOccured"));
        }
    }
    private String getSiteRoot()
    {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpServletRequest request = (HttpServletRequest) context.getExternalContext().getRequest();
        return request.getContextPath();
    }
    public String prepareLogin()
    {
        return "/user/login.xhtml";
    }
    public void checkLoginForStudent() {
        Students student = getFacade().checkStudentValid(current.getUserName(), current.getPassword());
        FacesContext context = FacesContext.getCurrentInstance();
        if (student == null) {
            context.getExternalContext().getSessionMap().put("IsStudent", student);
            JsfUtil.addErrorMessage("Login failed.");
        } else {
            context.getExternalContext().getSessionMap().put("IsStudent", student);
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect(getSiteRoot() + "/faces/user/course/List.xhtml");
            } catch (IOException ex) {
                Logger.getLogger(StaffController.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    public void NoLoginForStudent() {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            Staff staff = (Staff) context.getExternalContext().getSessionMap().get("IsStudent");
            if (staff == null) {
                FacesContext.getCurrentInstance().getExternalContext().redirect(getSiteRoot() + "/faces/user/login.xhtml");
            }
        } catch (IOException ex) {
            Logger.getLogger(StaffController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    public String getLoginStudent() {
        FacesContext context = FacesContext.getCurrentInstance();
        Students student = (Students) context.getExternalContext().getSessionMap().get("IsStudent");
        if(student!=null)
        {
        return student.getUserName();
        }
        return "";
    }
    public void LogoutForStudent() {
        try {
            FacesContext context = FacesContext.getCurrentInstance();
            context.getExternalContext().getSessionMap().put("IsStudent", null);
            FacesContext.getCurrentInstance().getExternalContext().redirect(getSiteRoot() + "/faces/user/course/List.xhtml");
        } catch (IOException ex) {
            Logger.getLogger(StaffController.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    private void updateCurrentItem() {
        int count = getFacade().count();
        if (selectedItemIndex >= count) {
            // selected index cannot be bigger than number of items:
            selectedItemIndex = count - 1;
            // go to previous page if last page disappeared:
            if (pagination.getPageFirstItem() >= count) {
                pagination.previousPage();
            }
        }
        if (selectedItemIndex >= 0) {
            current = getFacade().findRange(new int[]{selectedItemIndex, selectedItemIndex + 1}).get(0);
        }
    }

    public DataModel getItems() {
        if (items == null) {
            items = getPagination().createPageDataModel();
        }
        return items;
    }

    private void recreateModel() {
        items = null;
    }

    private void recreatePagination() {
        pagination = null;
    }

    public String next() {
        getPagination().nextPage();
        recreateModel();
        return "List";
    }

    public String previous() {
        getPagination().previousPage();
        recreateModel();
        return "List";
    }
    
    //added by HungNM
    public String getGenderStr(int gender)
    {
        if(gender == 1) return "Male";
        else if(gender == 0) return "FeMale";
        else return "Unknown";
    }
    
    public SelectItem[] getItemsAvailableSelectMany() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), false);
    }

    public SelectItem[] getItemsAvailableSelectOne() {
        return JsfUtil.getSelectItems(ejbFacade.findAll(), true);
    }

    @FacesConverter(forClass = Students.class)
    public static class StudentsControllerConverter implements Converter {

        public Object getAsObject(FacesContext facesContext, UIComponent component, String value) {
            if (value == null || value.length() == 0) {
                return null;
            }
            StudentsController controller = (StudentsController) facesContext.getApplication().getELResolver().
                    getValue(facesContext.getELContext(), null, "studentsController");
            return controller.ejbFacade.find(getKey(value));
        }

        java.lang.Integer getKey(String value) {
            java.lang.Integer key;
            key = Integer.valueOf(value);
            return key;
        }

        String getStringKey(java.lang.Integer value) {
            StringBuffer sb = new StringBuffer();
            sb.append(value);
            return sb.toString();
        }

        public String getAsString(FacesContext facesContext, UIComponent component, Object object) {
            if (object == null) {
                return null;
            }
            if (object instanceof Students) {
                Students o = (Students) object;
                return getStringKey(o.getStudentId());
            } else {
                throw new IllegalArgumentException("object " + object + " is of type " + object.getClass().getName() + "; expected type: " + Students.class.getName());
            }
        }
    }
}
